//
//  ZPConfirmOrderViewController.m
//  ZPIOSEducation
//
//  Created by mini1 on 2016/12/7.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "ZPConfirmOrderViewController.h"
#import "ZPOrderPaySateTabCell.h"
#import "ZPOdrerClassNameTabViewCell.h"
#import "ZPOrderPayMethodTabViewCell.h"
#import "ZPOrderClassDeTabViewCell.h"
#import "OrderCreateViewController.h"

#define CancelAlertTag  1000
#define DeleteAlertTag  2000

@interface ZPConfirmOrderViewController () <UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
{
    NSMutableDictionary  *dataDic;
}

@property (weak, nonatomic) IBOutlet UITableView *mainTableView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *cancelOrder; // 取消订单
@property (weak, nonatomic) IBOutlet UIButton *toPay;      // 去支付
@property (weak, nonatomic) IBOutlet UIButton *deleteOrder; // 删除订单

@end


@implementation ZPConfirmOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"订单详情";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhenpin_back"] style:UIBarButtonItemStylePlain target:self action:@selector(navLeftButtonClick)];
    
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    
    self.bottomView.hidden = YES;
    
    dataDic = [[NSMutableDictionary  alloc] init];
    [self  requestData];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)refreshBottomView
{
    self.bottomView.hidden = YES;
    self.deleteOrder.hidden = YES;
    self.cancelOrder.hidden = YES;
    self.toPay.hidden = YES;
    NSInteger  orderStatus = [[dataDic  objectForKey:@"orderStatus"] integerValue];
    switch (orderStatus) {
        case 0:
            
            break;
        case 1:
            self.bottomView.hidden = NO;
            self.deleteOrder.hidden = NO;
            break;
        case 2:
            self.bottomView.hidden = NO;
            self.deleteOrder.hidden = NO;
            break;
        case 3:
            self.bottomView.hidden = NO;
            self.cancelOrder.hidden = NO;
            self.toPay.hidden = NO;
            break;
            
        default:
            
            break;
    }
}

#pragma mark - Button Actions
#pragma mark 导航栏左边按钮
- (void)navLeftButtonClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 状态按钮点击
- (IBAction)statusButtonClick:(id)sender
{
    UIButton  *tempBtn = (UIButton  *)sender;
    NSString  *titleStr = tempBtn.titleLabel.text;
    if ([titleStr  isEqualToString:@"取消订单"]) {
        UIAlertView  *alertView = [[UIAlertView alloc] initWithTitle:@"确认取消订单吗？" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.tag = CancelAlertTag;
        [alertView  show];
    }else if ([titleStr  isEqualToString:@"去支付"]) {
        OrderCreateViewController  *viewController = [[OrderCreateViewController alloc] initWithNibName:@"OrderCreateViewController" bundle:nil];
        viewController.orderSn = [NSString  stringWithFormat:@"%@",[dataDic  objectForKey:@"orderSn"]];
        viewController.needPay = [NSString  stringWithFormat:@"%@",[dataDic  objectForKey:@"totalAmount"]];
        viewController.popBack=YES;
        [self.navigationController  pushViewController:viewController animated:YES];
    }else if ([titleStr  isEqualToString:@"删除订单"]) {
        UIAlertView  *alertView = [[UIAlertView alloc] initWithTitle:@"确认删除订单吗？" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.tag = DeleteAlertTag;
        [alertView  show];
    }
}


#pragma mark - 网络相关
- (void)requestData
{
    if (!self.orderSn) {
        return;
    }
    [self  showHudithString:@"加载中..."];
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"],@"memberId",[NSString stringWithFormat:@"%@",self.orderSn],@"orderSn", nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIUC@"centerorders/getorderdetail.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            [dataDic  removeAllObjects];
            if ([[responseObject  objectForKey:@"result"] isKindOfClass:[NSDictionary  class]]) {
                [dataDic  addEntriesFromDictionary:[responseObject  objectForKey:@"result"]];
                [self.mainTableView  reloadData];
                [self  refreshBottomView];
            }
            
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
        
    }];
}

#pragma mark 取消订单
- (void)sendCancelOrderRequest
{
    [self  showHudithString:@"发送中..."];
    
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"],@"memberId",[NSString stringWithFormat:@"%@",[dataDic  objectForKey:@"orderSn"]],@"orderSn", nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIUC@"centerorders/cancelorder.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"isOk"] boolValue]) {
                [[NSNotificationCenter  defaultCenter] postNotificationName:@"refreshOrderList" object:nil];
                [self  requestData];
            }
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
        
    }];
}

#pragma mark 删除订单
- (void)sendDeleteOrderRequest
{
    [self  showHudithString:@"发送中..."];
    
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"],@"memberId",[NSString stringWithFormat:@"%@",[dataDic  objectForKey:@"orderSn"]],@"orderSn", nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIUC@"centerorders/deleteOrder.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"isOk"] boolValue]) {
                [[NSNotificationCenter  defaultCenter] postNotificationName:@"refreshOrderList" object:nil];
                [self.navigationController  popViewControllerAnimated:YES];
            }
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
        
    }];
}


#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (dataDic.count > 0) {
        return 7;
    }else {
        return 0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 5) {
        return 3;
    }else if (section == 6) {
        return 2;
    }else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.;
    }else if (section == 5) {
        return 1.;
    }else if (section == 6) {
        return 1.;
    }else {
        return 8.;
    }
}

- (UIView  *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView  *tempView = [[UIView  alloc] init];
    tempView.backgroundColor = [UIColor  clearColor];
    return tempView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger  section = [indexPath  section];
    if (section == 0) {
        return 45.;
    }else if (section == 2) {
        return 113.;
    }else {
        if (section == 5 || section == 6) {
            return 31.;
        }else {
            return 45.;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = [indexPath section];
    NSInteger  row = [indexPath  row];
    if (section == 0) {
        static NSString *CellIdentifier = @"ZPOrderPaySateTabCell";
        ZPOrderPaySateTabCell  *cell = (ZPOrderPaySateTabCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ZPOrderPaySateTabCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        NSInteger  orderStatus = [[dataDic  objectForKey:@"orderStatus"] integerValue];
        switch (orderStatus) {
            case 0:
                [cell.statusBtn  setImage:[UIImage  imageNamed:@"OrderStatus_WaitVerify"] forState:UIControlStateNormal];
                [cell.statusBtn  setTitle:@"待审核" forState:UIControlStateNormal];
                [cell.statusBtn  setTitleColor:[UIColor  blackColor] forState:UIControlStateNormal];
                break;
            case 1:
                [cell.statusBtn  setImage:[UIImage  imageNamed:@"OrderStatus_Finish"] forState:UIControlStateNormal];
                [cell.statusBtn  setTitle:@"订单已完成" forState:UIControlStateNormal];
                [cell.statusBtn  setTitleColor:RGBACOLOR(33, 164, 255, 1.) forState:UIControlStateNormal];
                break;
            case 2:
                [cell.statusBtn  setImage:[UIImage  imageNamed:@"OrderStatus_Cancel"] forState:UIControlStateNormal];
                [cell.statusBtn  setTitle:@"订单已取消" forState:UIControlStateNormal];
                [cell.statusBtn  setTitleColor:[UIColor  blackColor] forState:UIControlStateNormal];
                break;
            case 3:
                [cell.statusBtn  setImage:[UIImage  imageNamed:@"OrderStatus_WaitPay"] forState:UIControlStateNormal];
                [cell.statusBtn  setTitle:@"待付款" forState:UIControlStateNormal];
                [cell.statusBtn  setTitleColor:RGBACOLOR(255, 86, 86, 1.) forState:UIControlStateNormal];
                break;
                
            default:
                [cell.statusBtn  setImage:nil forState:UIControlStateNormal];
                [cell.statusBtn  setTitle:@"" forState:UIControlStateNormal];
                break;
        }
        
        return cell;
    }else if (section == 2) {
        static NSString *CellIdentifier = @"ZPOdrerClassNameTabViewCell";
        ZPOdrerClassNameTabViewCell  *cell = (ZPOdrerClassNameTabViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ZPOdrerClassNameTabViewCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        [cell.studentImgView  sd_setImageWithURL:[NSURL  URLWithString:[NSString  stringWithFormat:@"%@",[dataDic  objectForKey:@"teacherUrl"]]] placeholderImage:[UIImage  imageNamed:@"girl_image"]];
        cell.studentName.text = [NSString  stringWithFormat:@"%@",[dataDic  objectForKey:@"teacherName"]];
        cell.className.text = [NSString  stringWithFormat:@"%@",[dataDic  objectForKey:@"className"]];
        cell.classDate.text = [NSString  stringWithFormat:@"%@",[dataDic  objectForKey:@"time"]];
        cell.classAddress.text = [NSString  stringWithFormat:@"%@",[dataDic  objectForKey:@"schoolName"]];
        
        return cell;
    }else {
        if (section == 5 || section == 6) {
            static NSString *CellIdentifier = @"ZPOrderClassDeTabViewCell";
            ZPOrderClassDeTabViewCell  *cell = (ZPOrderClassDeTabViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"ZPOrderClassDeTabViewCell" owner:self options:nil] lastObject];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.heaterTitle.text = @"";
            cell.detailTitle.text = @"";
            cell.detailTitle.font = [UIFont  systemFontOfSize:14.];
            
            if (section == 5) {
                cell.detailTitle.textColor = RGBACOLOR(51, 51, 51, 1.);
                cell.detailTitle.textAlignment = NSTextAlignmentRight;
                
                if (row == 0) {
                    cell.heaterTitle.text = @"课次";
                    cell.detailTitle.text = [NSString  stringWithFormat:@"%@次",[dataDic  objectForKey:@"courseNum"]];
                }else if (row == 1) {
                    cell.heaterTitle.text = @"课时费";
                    cell.detailTitle.text = [NSString  stringWithFormat:@"￥%@",[dataDic  objectForKey:@"scheduleCost"]];
                }else if (row == 2) {
                    cell.heaterTitle.text = @"课程总价";
                    cell.detailTitle.text = [NSString  stringWithFormat:@"￥%@",[dataDic  objectForKey:@"totalAmount"]];
                    cell.detailTitle.font = [UIFont  boldSystemFontOfSize:14.];
                }
                
            }else {
                cell.detailTitle.textColor = RGBACOLOR(153, 153, 153, 1.);
                cell.detailTitle.textAlignment = NSTextAlignmentLeft;
                
                if (row == 0) {
                    cell.heaterTitle.text = @"订 单 号：";
                    cell.detailTitle.text = [NSString  stringWithFormat:@"%@",[dataDic  objectForKey:@"orderSn"]];
                }else if (row == 1) {
                    cell.heaterTitle.text = @"下单时间：";
                    cell.detailTitle.text = [NSString  stringWithFormat:@"%@",[dataDic  objectForKey:@"orderTime"]];
                }
                
            }
            
            return cell;
        }else {
            static NSString *CellIdentifier = @"ZPOrderPayMethodTabViewCell";
            ZPOrderPayMethodTabViewCell  *cell = (ZPOrderPayMethodTabViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"ZPOrderPayMethodTabViewCell" owner:self options:nil] lastObject];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.heaterTitle.text = @"";
            cell.detailTitle.text = @"";
            cell.detailTitle.textColor = RGBACOLOR(153, 153, 153, 1.);
            cell.detailTitle.font = [UIFont  systemFontOfSize:12.];
            
            if (section == 1) {
                cell.heaterTitle.text = @"学生";
                NSString  *phoneSectureStr = @"";
                NSString  *stuPhone = [dataDic  objectForKey:@"stuPhone"];
                if (stuPhone && ![stuPhone  isEqual:[NSNull  null]]) {
                    phoneSectureStr = [NSString  stringWithFormat:@"%@",stuPhone];
                }
                NSInteger length = phoneSectureStr.length;
                if (length > 7) {
                    for (int i = 0; i < length; i++) {
                        if (i > 2 && i < length - 4) {
                            phoneSectureStr = [phoneSectureStr  stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@"*"];
                        }
                    }
                }
                cell.detailTitle.text = [NSString  stringWithFormat:@"%@   %@",[dataDic  objectForKey:@"stuName"],phoneSectureStr];
            }else if (section == 3) {
                cell.heaterTitle.text = @"发票";
                cell.detailTitle.text = @"请与前台联系确定发票领取时间、地点";
            }else if (section == 4) {
                cell.heaterTitle.text = @"支付方式";
                cell.detailTitle.text = [NSString  stringWithFormat:@"%@",[dataDic  objectForKey:@"paymentName"]];
                cell.detailTitle.textColor = RGBACOLOR(33, 164, 235, 1.);
                cell.detailTitle.font = [UIFont  systemFontOfSize:14.];
            }
            
            return cell;
        }
    }
    
}

#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        if (alertView.tag == CancelAlertTag) {
            [self  sendCancelOrderRequest];
        }else if (alertView.tag == DeleteAlertTag) {
            [self  sendDeleteOrderRequest];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
